<template>
  <div>
    <!-- Tab切换 -->
    <div class="tabs" ref="nav">
      <div ref="tabs" v-for="(item, index) in tabs" :key="index" @click="changeTab(index, item.id)"
        :class="{ active: currentIndex === index }">
        {{ item.classname }}
      </div>
    </div>

    <!-- Swiper容器 -->
    <div class="swiper-container" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
      <div ref="swiperWrapper" class="swiper-wrapper" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
        <div v-for="(item, index) in tabs" :key="index" class="swiper-slide">
          <div v-for="items,index in lists">{{ items.title }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['tabs', 'lists'],
  methods() {
    console.log(this.list, 999);
  },
  data() {
    return {
      // tabs: ['Tab 1', 'Tab 2', 'Tab 3'],
      currentIndex: 0,
      startX: 0,
      moveX: 0,
      isTouching: false,
      
    };
  },
  methods: {
    changeTab(index) {
      // 切换Tab时更新当前索引
      this.currentIndex = index;
      this.$emit('changeTab', this.currentIndex + 1)
      // 计算滚动位置以使单击的选项卡居中
      const nav = this.$refs.nav; // 获取选项卡导航栏的引用
      const tab = this.$refs.tabs[index]; // 获取当前选中的选项卡的引用
      const scrollLeft = tab.offsetLeft - (nav.clientWidth - tab.clientWidth) / 2;  // 计算滚动左侧位置以居中当前选项卡
      nav.scrollLeft = Math.max(0, Math.min(scrollLeft, nav.scrollWidth - nav.clientWidth));  // 设置滚动位置，确保在合理的范围内
    },
    onTouchStart(event) {
      this.isTouching = true;
      this.startX = event.touches[0].clientX;
      this.moveX = 0;
    },
    onTouchMove(event) {
      if (!this.isTouching) return;
      this.moveX = event.touches[0].clientX - this.startX;
    },
    onTouchEnd() {
      if (!this.isTouching) return;
      this.isTouching = false;
      const threshold = 50; // 设置滑动切换的阈值
      if (this.moveX > threshold && this.currentIndex > 0) {
        this.changeTab(this.currentIndex - 1);
      } else if (this.moveX < -threshold && this.currentIndex < this.tabs.length - 1) {
        this.changeTab(this.currentIndex + 1);
      }
    },
  },
};
</script>

<style>
/* 添加一些样式来美化外观 */
.tabs {
  display: flex;
  overflow-x: scroll;
  -webkit-overflow-scrolling: touch;

  &::-webkit-scrollbar {
    display: none;
  }
}

.tabs div {
  flex: 0 0 auto;
  padding: 10px 15px;
  font-size: 16px;
  cursor: pointer;
}

.tabs div.active {
  font-size: 20px;
  color: #FC5C82;
  font-weight: 700;
}

.swiper-container {
  width: 100%;
  overflow: hidden;
  position: relative;
  touch-action: pan-y;
}

.swiper-wrapper {
  display: flex;
  transition: transform 0.3s ease-in-out;
}

.swiper-slide {
  flex: 0 0 100%;
  box-sizing: border-box;
  text-align: center;
  padding: 20px;
  background-color: #f1f1f1;
}
</style>